package com.freecloud.whispered.oss.service;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.whispered.oss.config.CloudStorageConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;

/**
 * 七牛云存储
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-25 15:41
 */
public class QiniuCloudStorageService extends CloudStorageService{
    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private String token;

    public QiniuCloudStorageService(CloudStorageConfig config){
        this.config = config;

        //初始化
        init();
    }

    private void init(){
        uploadManager = new UploadManager(new Configuration(Zone.autoZone()));

        Auth auth = Auth.create(config.getQiniuAccessKey(), config.getQiniuSecretKey());

        bucketManager = new BucketManager(auth,new Configuration(Zone.autoZone()));

        token = auth.uploadToken(config.getQiniuBucketName());


    }

    @Override
    public String upload(byte[] data, String path) {
        try {
            Response res = uploadManager.put(data, path, token);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson ().fromJson(res.bodyString(), DefaultPutRet.class);

            Console.log ("七牛hash:" + putRet.hash);
            Console.log ("七牛key:" + putRet.key);

            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        } catch (Exception e) {
            throw new RRException("上传文件失败，请核对七牛配置信息", e);
        }

        return config.getQiniuDomain() + "/" + path;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            byte[] data = IOUtils.toByteArray(inputStream);
            return this.upload(data, path);
        } catch (IOException e) {
            throw new RRException("上传文件失败", e);
        }
    }

    @Override
    public String upload(byte[] data) {
        return upload(data, getPath(config.getQiniuPrefix()));
    }

    @Override
    public String upload(InputStream inputStream) {
        return upload(inputStream, getPath(config.getQiniuPrefix()));
    }

    @Override
    public void delete(String url) {
        if(StrUtil.isEmpty (url))
        {
            return;
        }

        String fileKey = getFileKey (url);

        try
        {
            Response res = bucketManager.delete (config.getQiniuBucketName(),fileKey);

            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
        }
        catch(QiniuException e)
        {
            throw new RRException ("删除文件失败",e);
        }
    }
}
